package com.example.easyutils.curstartfortune;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.easyutils.BaseActivity;
import com.example.easyutils.HistoryToday;
import com.example.easyutils.R;
import com.example.easyutils.httputil.HttpGetRequest;
import com.example.easyutils.util.MyTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class StartFortune extends BaseActivity {
    ZLoadingDialog dialog = new ZLoadingDialog(StartFortune.this);//加载页面动画
    private List<String> list = new ArrayList<String>();
    private TextView textview,fortuneText,birthdayText,dataText,luckyColorText,luckyNumbersText,matchConstellationText,
            commentsText,comprehensiveLuckText,loveText,academicText,wealthLuckText,
            healthLuckText,healthNum,discussNum;
    private RatingBar healthIndexText, discussIndexText;
    private Spinner spinnertext;
    private String warnStr = "";
    private ArrayAdapter<String> adapter;
    private Map getFortuneData;
    private static final int GET_FORTUNE_CODE = 1,ERROR_CODE = 2,WARN_CODE = 3;
    Handler handler = new Handler()
    {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_FORTUNE_CODE:
                    Log.d("获取到参数：",getFortuneData.toString());
                            fortuneText.setText(getFortuneData.get("fortune").toString());
                            birthdayText.setText(getFortuneData.get("birthday").toString());
                            dataText.setText(getFortuneData.get("data").toString());
                            luckyColorText.setText(getFortuneData.get("lucky_color").toString());
                            luckyNumbersText.setText(getFortuneData.get("lucky_numbers").toString());
                            matchConstellationText.setText(getFortuneData.get("match_constellation").toString());
                            commentsText.setText(getFortuneData.get("comments").toString());
                            comprehensiveLuckText.setText(getFortuneData.get("comprehensive_luck").toString());
                            loveText.setText(getFortuneData.get("love").toString());
                            academicText.setText(getFortuneData.get("academic").toString());
                            wealthLuckText.setText(getFortuneData.get("wealth_luck").toString());
                            healthLuckText.setText(getFortuneData.get("health_luck").toString());
                            float f = (float) (Integer.parseInt(getFortuneData.get("health_index").toString().replace("%","")))/20;
                            float f1 = (float) (Integer.parseInt(getFortuneData.get("discuss_index").toString().replace("%","")))/20;
                            healthIndexText.setRating(f);
                            discussIndexText.setRating(f1);
                            discussNum.setText(f1+"");
                            healthNum.setText(f+"");
                            dialog.cancel();
                case ERROR_CODE:
                    Toast.makeText(StartFortune.this,"出错啦",Toast.LENGTH_LONG).show();
                    break;
                case WARN_CODE:
                    Toast.makeText(StartFortune.this,"出错啦",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
    public void onCreate(Bundle savedlnstanceState) {
        super.onCreate(savedlnstanceState);
        setContentView(R.layout.start_fortune);
        init();


        //第一步：定义下拉列表内容
        list.add("白羊座");
        list.add("金牛座");
        list.add("双子座");
        list.add("巨蟹座");
        list.add("狮子座");
        list.add("处女座");
        list.add("天秤座");
        list.add("天蝎座");
        list.add("射手座");
        list.add("摩羯座");
        list.add("水瓶座");
        list.add("双鱼座");
        textview = (TextView) findViewById(R.id.textView1);
        spinnertext = (Spinner) findViewById(R.id.spinner1);
        //第二步：为下拉列表定义一个适配器
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
        //第三步：设置下拉列表下拉时的菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        spinnertext.setAdapter(adapter);
        //第五步：添加监听器，

        spinnertext.setOnItemSelectedListener(new ProvOnItemSelectedListener());

        //将spinnertext添加到OnTouchListener对内容选项触屏事件处理
        spinnertext.setOnTouchListener(new Spinner.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                // 将mySpinner隐藏
//                v.setVisibility(View.INVISIBLE);
                Log.i("spinner", "Spinner Touch事件被触发!");
                return false;
            }
        });

        //焦点改变事件处理
        spinnertext.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
//                v.setVisibility(View.VISIBLE);
                Log.i("spinner", "Spinner F ocusChange事件被触发！");
            }
        });

    }

    private void init(){
        fortuneText = (TextView)findViewById(R.id.fortune);
        birthdayText = (TextView)findViewById(R.id.birthday);
        dataText = (TextView)findViewById(R.id.today_date);
        healthIndexText = (RatingBar) findViewById(R.id.health_index);
        discussIndexText = (RatingBar)findViewById(R.id.discuss_index);
        luckyColorText = (TextView)findViewById(R.id.lucky_color);
        luckyNumbersText = (TextView)findViewById(R.id.lucky_number);
        matchConstellationText = (TextView)findViewById(R.id.match_constellation);
        commentsText = (TextView)findViewById(R.id.comments);
        comprehensiveLuckText = (TextView)findViewById(R.id.comprehensive_luck);
        loveText = (TextView)findViewById(R.id.love);
        academicText = (TextView)findViewById(R.id.academic);
        wealthLuckText = (TextView)findViewById(R.id.wealth_luck);
        healthLuckText = (TextView)findViewById(R.id.health_luck);
        healthNum = (TextView)findViewById(R.id.health_num);
        discussNum = (TextView)findViewById(R.id.discuss_num);
    }

    //OnItemSelected监听器
    private class  ProvOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> adapters, View view, int position, long id) {

            dialog.setLoadingBuilder(Z_TYPE.LEAF_ROTATE)//设置类型
                    .setLoadingColor(Color.RED)//颜色
                    .setHintText("Loading...")
                    .setHintTextSize(16) // 设置字体大小 dp
                    .setHintTextColor(Color.GRAY)  // 设置字体颜色
                    .setDurationTime(0.5) // 设置动画时间百分比 - 0.5倍
                    .setDialogBackgroundColor(Color.parseColor("#CC111111")) // 设置背景色，默认白色
                    .show();
            //获取选择的项的值
            // TODO Auto-generated method stub
            /* 将所选spinnertext的值带入myTextView中*/
            textview.setText("您选择的星座是:" + adapter.getItem(position));
            Log.d("您选择的星座是:",position+"");
            getSatrtFortune(position+1);
            /* 将 spinnertext 显示^*/
            adapters.setVisibility(View.VISIBLE);
            String sInfo = adapters.getItemAtPosition(position).toString();
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            String sInfo = "什么也没选！";
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();

        }
    }

    private void getSatrtFortune(int position){//运势
        Log.d("您选择的星座是11:",position+"");
        HttpGetRequest.sendOkHttpGetRequst("http://api.63code.com/fortune_today/api.php?fortune="+position,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("失败：","error");
                        handler.sendEmptyMessage(ERROR_CODE);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        Log.d("成功：",responseData);
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, Object>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,Object> dataDetail = gson.fromJson(responseData,new TypeToken<Map<String,Object>>(){

                        }.getType());

                        Log.d("Long",dataDetail.get("code")+"");
                        String code = (String) dataDetail.get("code");
                        if(code.equals("1")){
                            getFortuneData = new HashMap();
                            getFortuneData = dataDetail;
                            handler.sendEmptyMessage(GET_FORTUNE_CODE);
                            Log.d("fortune",dataDetail+"");
                            Log.d("fortune", (String) dataDetail.get("fortune"));
                        }else{
                            warnStr = (String) dataDetail.get("msg");
                            handler.sendEmptyMessage(WARN_CODE);
                        }

                    }
                });
    }

//    http://api.63code.com/fortune_today/api.php?fortune=1

}
